﻿using System.Data;
using System.IO;
using DataScripter.Database;
using DataScripter.Database.SqlServer;
using DataScripter.Scripting.OutputDestinations;

namespace DataScripter.Scripting.Output.Sql.SqlServer
{
    public class SkipIfExistsElseInsertOutputProducer : SqlServerOutputProducer
    {
        public SkipIfExistsElseInsertOutputProducer(IOutputDestination outputDestination) : base(outputDestination)
        {
        }

        protected override void HandleRecord(IDataReader reader, StreamWriter streamWriter, bool isFirstRecord)
        {
            ScriptTableNamePkFound(TableScriptRequest, reader, streamWriter);
            FieldInfo pk = TableScriptRequest.TableStructure.PrimaryKeyFields[0];
            string pkValueRaw = pk.ReadRawValue(reader).ToString();
            string pkName = pk.ColumnName;
            ScriptSpecialFieldTreatments(TableScriptRequest, reader, streamWriter, OutputContext, OutputDestination.Resolve<SqlServerDb>());
            streamWriter.WriteLine(string.Format("IF NOT EXISTS(SELECT 1 FROM [{1}] WHERE [{2}] = '{0}' )", pkValueRaw, TableScriptRequest.TableName, pkName));
            streamWriter.WriteLine("  BEGIN");
            streamWriter.WriteLine("    " + ProduceInsertSqlForCurrentRecord(TableScriptRequest, reader, isFirstRecord));
            streamWriter.WriteLine(string.Format("    PRINT 'Row with ID {0} inserted into table {1}.'", pkValueRaw, TableScriptRequest.TableName));
            streamWriter.WriteLine("  END");
            streamWriter.WriteLine("ELSE");
            streamWriter.WriteLine("  BEGIN");
            streamWriter.WriteLine(string.Format("    PRINT 'Row with ID {0} already exists in table {1}, skipping.'", pkValueRaw, TableScriptRequest.TableName));
            streamWriter.WriteLine("  END");
        }
    }
}